package com.xjnt.mnui.service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import com.xjnt.frameworks.annotation.Service;
import com.xjnt.frameworks.core.BaseService;
import com.xjnt.frameworks.plugin.sql.consts.FetchMode;
import com.xjnt.frameworks.plugin.sql.criterion.Restrictions;
import com.xjnt.frameworks.plugin.sql.criterion.SqlCriteria;
import com.xjnt.frameworks.plugin.sql.criterion.expression.Order;
import com.xjnt.frameworks.web.constants.SearchType;
import com.xjnt.mnui.entity.CardRule;
import com.xjnt.mnui.entity.Portal;

@Service
public class CardRuleService extends BaseService<CardRule> {

	@Override
	public CardRule getModel() {
		return CardRule.me;
	}
	
	@Override
	protected SqlCriteria getCriteria(Map<String, String[]> conditions,
			SearchType searchType) {
		SqlCriteria criteria = new SqlCriteria(getModel(), "cardRule");
		criteria.addRelation(Portal.me, "portal", FetchMode.FETCH);
		criteria.add(Restrictions.eqProp("cardRule.portalid", "portal.uuid"));
		if (conditions != null) {
			Map<String, Class<?>> columnMap = getModel().getTable().getColumnTypeMap();
			Set<Entry<String, String[]>> setCondition = conditions.entrySet();
			Iterator<Entry<String, String[]>> itCondition = setCondition.iterator();
			while (itCondition.hasNext()) {
				Entry<String, String[]> entry = itCondition.next();
				String conditionName = entry.getKey();
				String[] conditionVal = entry.getValue();
				String[] tmpNames = conditionName.split("\\.");
				String colName = conditionName;
				if(tmpNames.length > 1){
					colName = tmpNames[1];
				}
				boolean hasColumn = getModel().getTable().hasColumnLabel(colName);
				if(hasColumn){
					Class<?> colType = columnMap.get(colName);
					combine(criteria, criteria.getAlias() + "." + colName, conditionVal, colType, searchType);
				}
			}
			Object[] sortName = conditions.get("sortName");
			Object[] sortOrder = conditions.get("sortOrder");
			orderCondition(criteria, sortName, sortOrder);
		}
		return criteria;
	}

	@Override
	public List<CardRule> findAll() {
		
		List<CardRule> lstRules = CacheKit.get("Base-System", "CARD_ALL_RULE", new IDataLoader(){
			@Override
			public Object load() {
				SqlCriteria criteria = new SqlCriteria(getModel(), "cardRule");
				criteria.addRelation(Portal.me, "portal", FetchMode.FETCH);
				criteria.add(Restrictions.eqProp("cardRule.portalid", "portal.uuid"));
				criteria.addOrder(Order.asc("cardRule.level"));
				return getModel().find(criteria.toSql());
			}
		});
		return lstRules;
	}
	
	@Override
	public void clearCache() {
		CacheKit.remove("Base-System", "CARD_ALL_RULE");
	}
}
